package com.zengdb.jdbc.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zengdb.jdbc.dao.IStudentDAO;
import com.zengdb.jdbc.dao.impl.StudentDAOImpl;
import com.zengdb.jdbc.domain.Student;
import com.zengdb.jdbc.util.StringUtil;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private IStudentDAO dao = new StudentDAOImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String cmd = req.getParameter("cmd");
		if ("edit".equals(cmd)) {
			edit(req, resp);
		} else if ("delete".equals(cmd)) {
			delete(req, resp);
		} else if ("save".equals(cmd)) {
			save(req, resp);
		} else {
			list(req, resp);
		}
	}

	private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1：接收参数，封装成对象
		//2：调用业务方法
		List<Student> list = dao.queryList();
		req.setAttribute("list", list);
		//3：处理页面跳转
		req.getRequestDispatcher("/WEB-INF/views/student/list.jsp").forward(req, resp);
		;
	}

	//新增和编辑
	private void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1：接收参数，封装成对象
		String id = req.getParameter("id");
		//2：调用业务方法
		if (StringUtil.hasLength(id)) { //id有值时为修改操作
			Student stu = dao.queryOne(Long.parseLong(id));
			req.setAttribute("stu", stu);
		} 
		//3：处理页面跳转
		req.getRequestDispatcher("/WEB-INF/views/student/edit.jsp").forward(req, resp);
	}

	private void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//1：接收参数，封装成对象
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		Student stu = new Student(null, name, Integer.parseInt(age));
		//2：调用业务方法
		if (StringUtil.hasLength(id)) { //id有值时为修改操作
			stu.setId(Long.parseLong(id));
			dao.modify(stu);
		} else {
			dao.save(stu);
		}
		//3：处理页面跳转
		resp.sendRedirect("/student");
	}

	private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		//1:接收参数，封装成对象
		String id = req.getParameter("id");
		//2：调用业务方法
		dao.delete(Long.parseLong(id));
		//3：处理页面跳转
		resp.sendRedirect("/student");
	}

}